package network

import (
	"log"
)

var connection StringBoolMap
var connectionMap StringIntMap
var maxLimit = 3

// GetPortNumber gets port number for server api
func GetPortNumber(portNum string) string {
	// Simple implementation - can be enhanced if needed
	tmpPort := portNum
	if len(tmpPort) > 0 && tmpPort[0] == ':' {
		// Extract port and add 1000
		portStr := tmpPort[1:]
		tmpPortInt, err := StringToInt64(portStr)
		if err == nil {
			return ":" + Int64ToString(tmpPortInt+1000)
		}
	}
	return tmpPort
}

// IsNotLive checks if a node is not live
func IsNotLive(key string) bool {
	result, exist := connection.Get(key)
	if exist {
		return result
	}
	return false
}

// NotLive sets node to not alive
func NotLive(key string) {
	v, exist := connectionMap.Get(key)
	if !exist {
		connectionMap.Insert(key, 0)
	} else {
		connectionMap.Insert(key, v+1)
	}

	v, _ = connectionMap.Get(key)
	if v > maxLimit {
		connection.Insert(key, true)
	}
}

// SetLive sets node to live
func SetLive(key string) {
	connectionMap.Insert(key, 0)
	connection.Insert(key, false)
}

// StartConnectionManager starts connection manager
func StartConnectionManager() {
	log.Printf("starting connection manager")
	connection.Init()
	connectionMap.Init()
}

